//
//  SNOAuthViewController.m
//  SinaVboc
//
//  Created by V on 29/11/2016.
//  Copyright © 2016 仁忄. All rights reserved.
//

#import "SNOAuthViewController.h"
#import "SNUserAccountViewModel.h"

@interface SNOAuthViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation SNOAuthViewController

- (void)loadView {
    
    self.view = self.webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    
}

- (void)closeButtonDidClick:(UIButton *)sender {
    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)fillButtonDidClick:(UIButton *)sender {
    
    NSString *jsString = @"document.getElementById('userId').value = '15070264701', document.getElementById('passwd').value = '525888'";
    [_webView stringByEvaluatingJavaScriptFromString:jsString];
}



- (void)setupUI {
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" imageName:nil target:self action:@selector(closeButtonDidClick:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"填充" imageName:nil target:self action:@selector(fillButtonDidClick:)];
}


- (UIWebView *)webView {
    
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        
        NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",
                               client_id, redirect_uri];
        
        NSURL *url = [[NSURL alloc] initWithString:urlString];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [_webView loadRequest:request];
        
        _webView.delegate = self;
    }
    return _webView;
}


#pragma mark - webview delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [SVProgressHUD show];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [SVProgressHUD dismiss];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *urlString = request.URL.absoluteString;
    
    NSString *flag = @"code=";
    
    if ([urlString containsString:flag]) {
        
        NSString *query = request.URL.query;
        NSString *code = [query substringFromIndex:flag.length];
        
        [[SNUserAccountViewModel alloc] loadAccessToken:code finished:^(bool isSuccess) {
           
            if (!isSuccess) {
                [SVProgressHUD showErrorWithStatus:@"网络错误"];
                return ;
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kChoseRootViewController object:@"OAuth"];
            
        }];
        
        return NO;
    }
    return  YES;
}

- (void)dealloc {
    
    NSLog(@"oauth release");
}


@end



















































